<template>
  <div class="income-certificate-container">
    <span
      class="title"
      style="
        display: flex;
        justify-content: space-between;
        width: 234mm;
        margin: 0 auto;
        margin-bottom: 10px;
      "
    >
      <el-button
        type="primary"
        @click="$router.push('/main/renshi/renshizhidu')"
        icon="el-icon-back"
        >返回</el-button
      >
      <!-- <router-link to="/main/renshi/renshizhidu" style="position: absolute;top:10px; left: 10px;">返回</router-link> -->
      <span>
        <el-button
          type="success"
          icon="el-icon-check"
          @click="save"
          v-if="!isView"
          >保存</el-button
        >
        <el-button type="" icon="el-icon-menu" @click="goToList"
          >列表</el-button
        >
        <el-button type="info" icon="el-icon-printer" @click="printForm"
          >打印</el-button
        >
      </span>
    </span>
    <!-- <button @click="saveToPDF">打印pdf</button> -->
    <div
      v-for="index in 2"
      :key="index"
      style="display: flex; justify-content: center"
    >
      <div class="income-certificate">
        <h2>收入证明</h2>
        <p>
          兹证明
          <input
            v-model="employeeInfo.name"
            :disabled="isView || index === 2"
          />
          为我单位员工，身份证号码：<input
            style=""
            v-model="employeeInfo.idNumber"
            :disabled="isView || index === 2"
          />
        </p>
        <p>
          入职日期：<input
            v-model="employeeInfo.joinDate"
            :disabled="isView || index === 2"
          />
          至今仍在职。任职部门：<input
            v-model="employeeInfo.department"
            :disabled="isView || index === 2"
          />
          学历：<input
            v-model="employeeInfo.education"
            :disabled="isView || index === 2"
          />
        </p>
        <p>
          该员工税前月收入人民币：<input
            v-model="employeeInfo.income"
            :disabled="isView || index === 2"
          />
          元整，大写：<input
            v-model="employeeInfo.incomeInChinese"
            :disabled="isView || index === 2"
          />
        </p>
        <span style="text-align: left">
          <p>
            本证明仅限于该员工办理
            <input
              v-model="employeeInfo.usage"
              :disabled="isView || index === 2"
            />
            使用。
          </p>
          <p>
            经办人（签名）：<input
              v-model="employeeInfo.operator"
              :disabled="isView || index === 2"
            />
          </p>
          <p>
            签收人（签名）：<input
              v-model="employeeInfo.recipient"
              :disabled="isView || index === 2"
            />
          </p>
          <p>
            联系电话：0755-<input
              v-model="employeeInfo.phone"
              :disabled="isView || index === 2"
            />
          </p>
        </span>
        <span style="text-align: right">
          <p>
            单位名称（盖章）：<input
              v-model="employeeInfo.companyName"
              :disabled="isView || index === 2"
            />
            <span
              ><input
                v-model="employeeInfo.certificateYear"
                type="number"
                min="0"
                :disabled="isView || index === 2"
              />
              年<input
                v-model="employeeInfo.certificateMonth"
                type="number"
                min="0"
                :disabled="isView || index === 2"
              />
              月
              <input
                v-model="employeeInfo.certificateDay"
                type="number"
                min="0"
                :disabled="isView || index === 2"
              />日</span
            >
          </p>
        </span>
        <p>
          注：此证明一式二份，{{
            index === 1 ? "上联（个人）留存" : "下联（公司）留存"
          }}
        </p>
        <p style="display: flex; justify-content: space-between">
          <span>表单编号及版本：AM-JY-026 A/0</span>
          <span>保存期限：长期</span>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import { Message } from "element-ui";
import {
  saveIncomeCertificate,
  batchSaveIncomeCertificate,
  getIncomeCertificateDetail,
} from "@/api/incomeCertificate";
import { getPaymentProofList } from "@/api/paymentProof";

export default {
  data() {
    return {
      id: null,
      isView: false,
      isEdit: false,
      employeeInfo: {
        name: "",
        idNumber: "",
        joinDate: "",
        department: "",
        education: "",
        income: "",
        incomeInChinese: "",
        usage: "",
        operator: "",
        recipient: "",
        phone: "",
        companyName: "",
        certificateYear: "",
        certificateMonth: "",
        certificateDay: "",
      },
    };
  },
  created() {
    // 获取路由参数
    const { id, type } = this.$route.query;
    if (id) {
      this.id = id;
      if (type === "view") {
        this.isView = true;
      } else if (type === "edit") {
        this.isEdit = true;
      }
      console.log(
        "获取详情ID:",
        id,
        "查看模式:",
        this.isView,
        "编辑模式:",
        this.isEdit
      );
      this.getDetail(id);
    } else {
      console.log("没有ID参数，创建新表单");
    }
  },
  methods: {
    printForm() {
      // 创建一个样式元素
      const style = document.createElement("style");
      style.type = "text/css";
      style.media = "print";
      style.textContent = "@page { size: A4 landscape; }";
      // 将样式添加到文档头部
      document.head.appendChild(style);
      // 执行打印
      window.print();
      // 打印完成后移除样式
      document.head.removeChild(style);
    },
    // 获取详情
    async getDetail(id) {
      try {
        const response = await getIncomeCertificateDetail(id);
        if (response.data && response.data.code === 200) {
          const data = response.data.data;
          this.employeeInfo = data;
        } else {
          Message.error(response.data.message || "获取详情失败");
        }
      } catch (error) {
        console.error("获取详情错误：", error);
        Message.error("获取详情失败：" + error.message);
      }
    },

    // 跳转到列表页
    goToList() {
      this.$router.push("/main/renshi/renshizhidu/shouruzm/shouruzmList");
    },

    // 验证表单
    validateForm() {
      console.log("开始验证表单数据:", this.employeeInfo);
      // 验证表单
      const info = this.employeeInfo;
      if (!info.name) {
        Message.error("请填写员工姓名");
        return false;
      }
      if (!info.idNumber) {
        Message.error("请填写身份证号码");
        return false;
      }
      if (!info.joinDate) {
        Message.error("请填写入职日期");
        return false;
      }
      if (!info.department) {
        Message.error("请填写任职部门");
        return false;
      }
      if (!info.income) {
        Message.error("请填写税前月收入");
        return false;
      }
      return true;
    },

    // 保存数据
    async save() {
      if (!this.validateForm()) {
        return;
      }

      try {
        console.log("准备保存数据...");
        // 只提交一份数据
        const data = {
          id: this.id, // 如果是编辑模式，使用已有ID
          name: this.employeeInfo.name,
          idNumber: this.employeeInfo.idNumber,
          joinDate: this.employeeInfo.joinDate,
          department: this.employeeInfo.department,
          education: this.employeeInfo.education,
          income: this.employeeInfo.income,
          incomeInChinese: this.employeeInfo.incomeInChinese,
          usage: this.employeeInfo.usage,
          operator: this.employeeInfo.operator,
          recipient: this.employeeInfo.recipient,
          phone: this.employeeInfo.phone,
          companyName: this.employeeInfo.companyName,
          certificateYear: this.employeeInfo.certificateYear,
          certificateMonth: this.employeeInfo.certificateMonth,
          certificateDay: this.employeeInfo.certificateDay,
        };

        console.log("提交的数据:", data);
        const response = await saveIncomeCertificate(data);
        console.log("保存响应:", response);

        if (response.data && response.data.code === 200) {
          Message.success("保存成功");
          // 保存成功后跳转到列表页
          this.$router.push("/main/renshi/renshizhidu/shouruzm/shouruzmList");
        } else {
          console.error("保存失败:", response.data);
          Message.error(response.data?.message || "保存失败");
        }
      } catch (error) {
        console.error("保存错误：", error);
        Message.error("保存失败：" + (error.message || "未知错误"));
      }
    },

    // async saveToPDF() {
    //   const doc = new jsPDF("p", "pt", "a4");
    //   const elementList = document.querySelectorAll(".income-certificate");
    //   const pageHeight = 841.89;
    //   let positionY = 0;

    //   for (let i = 0; i < elementList.length; i++) {
    //     const element = elementList[i];
    //     await html2canvas(element).then((canvas) => {
    //       const imgData = canvas.toDataURL("image/png");
    //       const imgWidth = 522;
    //       const imgHeight = (canvas.height * imgWidth) / canvas.width;

    //       if (positionY + imgHeight > pageHeight) {
    //         // 如果当前图片超出页面高度，添加新页面
    //         doc.addPage();
    //         positionY = 0;
    //       }

    //       doc.addImage(imgData, "PNG", 40, positionY, imgWidth, imgHeight);
    //       positionY += imgHeight; // 添加一些间距
    //     });
    //   }

    //   doc.save("收入证明.pdf");
    // },
  },
};
</script>

<style scoped lang="scss">
.income-certificate-container {
  font-family: "宋体", sans-serif;
  padding: 20px;
   background-color: #f9f9f9; 
  border-radius: 8px;
  /* box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); */
  width: 297mm;
  margin: 0 auto;
  min-height: 100vh;
}

.income-certificate {
  border: 1px solid #000;
  padding: 30px;
  line-height: 30px;
  margin-bottom: 20px;
  /* width: 75%; */
  p {
    line-height: 2em;
  }
}

input {
  margin: 0;
  padding: 0;
  border: none;
  border-bottom: 1px solid #000;
  background-color: transparent;
  outline: none;
  /* 其他自定义样式 */
}

input[type="number"] {
  width: 60px;
  text-align: end;
}

input:disabled {
  background-color: #f5f7fa42;
  cursor: not-allowed;
  opacity: 0.7;
}

@media print {
  .title {
    display: none !important;
  }
  .income-certificate {
    page-break-after: always !important;
  }
  .income-certificate:last-child {
    page-break-after: avoid;
  }
}
</style>